﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.ScheduleJob.Common
{
    public class ExceptionHelper
    {
        /// <summary>
        /// 设置异常上下文
        /// </summary>
        /// <param name="e">异常对象</param>
        /// <param name="target">调用目标地址</param>
        /// <param name="serviceID">访问的目标服务ID</param>
        public static void SetContext(Exception e, string target, string targetServiceID)
        {
            if (e == null || e.Data == null)
                return;
            if (e.Data.Contains("ServerIP") == false)
                e.Data.Add("ServerIP", target);
            if (e.Data.Contains("TargetServiceID") == false)
                e.Data.Add("TargetServiceID", targetServiceID);
        }

        /// <summary>
        /// 获取异常上下文中的目标地址
        /// </summary>
        /// <param name="e">异常信息</param>
        /// <returns>目标地址</returns>
        public static string GetTargetFromContext(Exception e)
        {
            if (e == null || e.Data == null)
                return string.Empty;
            if (e.Data.Contains("ServerIP") == true)
                return Convert.ToString(e.Data["ServerIP"]);
            else
                return GetTargetFromContext(e.InnerException);
        }

        /// <summary>
        /// 获取异常上下文中的服务ID
        /// </summary>
        /// <param name="e">异常对象</param>
        /// <returns>服务ID</returns>
        public static string GetServiceIDFromContext(Exception e)
        {
            if (e == null || e.Data == null)
                return string.Empty;
            if (e.Data.Contains("TargetServiceID") == true)
                return Convert.ToString(e.Data["TargetServiceID"]);
            else
                return GetServiceIDFromContext(e.InnerException);
        }

        /// <summary>
        /// 设置异常为远程调用的异常
        /// </summary>
        /// <param name="e">异常对象</param>
        public static void SetRemoteException(Exception e)
        {
            if (e == null || e.Data == null)
                return;
            if (e.Data.Contains("IsRemoteException") == false)
                e.Data.Add("IsRemoteException", true);
        }

        /// <summary>
        /// 是否远程异常
        /// </summary>
        /// <param name="e">异常对象</param>
        /// <returns>true：远程异常，false：本地异常</returns>
        public static bool IsRemoteException(Exception e)
        {
            if (e == null || e.Data == null)
                return false;
            if (e.Data.Contains("IsRemoteException") == false)
                return false;
            else
                return true;
        }
    }
}
